package com.google.jessewilson.codesearch.ui;

import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A clipboard built on top of {@link java.awt.datatransfer.Clipboard} appropriate
 * for Swing applications.
 *
 * @author jessewilson
 */
public class JavaAwtClipboard implements Clipboard {

  public boolean setContents(String text) {
    java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection contents = new StringSelection(text);
    clipboard.setContents(contents, contents);
    return true;
  }

  public String getContents() {
    java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable contents = clipboard.getContents(this);
    if (!contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
      return null;
    }

    try {
      return (String) contents.getTransferData(DataFlavor.stringFlavor);
    } catch(UnsupportedFlavorException e) {
      Logger.getLogger(JavaAwtClipboard.class.getName())
          .log(Level.WARNING, "Failed to get clipboard contents", e);
      return null;
    } catch(IOException e) {
      Logger.getLogger(JavaAwtClipboard.class.getName())
          .log(Level.WARNING, "Failed to get clipboard contents", e);
      return null;
    }
  }
}
